<template>
  <div>
    <el-dialog v-model="articleStore.editFormVisible" title="修改文章" width="35%" @close="diaLogClose">
      <el-form
        :model="props.editInfo"
        status-icon
        label-width="120px"
        @submit.prevent
        :rules="rules"
        :validate-on-rule-change="false"
        ref="editArticleRef"
      >
        <!-- 文章 标题 -->
        <el-form-item label="文章标题" prop="article_title">
          <el-input v-model="props.editInfo.article_title" autocomplete="off" />
        </el-form-item>
        <!-- 文章 标签 -->
        <el-form-item label="文章标签" prop="article_labels">
          <el-checkbox-group v-model="props.editInfo.article_labels">
            <el-checkbox v-for="item in props.labels" :key="item.id" :label="item.id">{{ item.label_name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <!-- 文章 类型 -->
        <el-form-item label="文章类型" prop="article_type">
          <el-select v-model="props.editInfo.article_type">
            <el-option v-for="item in props.types" :key="item.id" :label="item.type_name" :value="item.id" />
          </el-select>
        </el-form-item>
        <!-- 上传封面 -->
        <el-form-item label="上传封面">
          <el-upload
            ref="uploadEdit"
            action="#"
            :auto-upload="false"
            :http-request="uploadAction"
            :before-upload="beforeUpload"
            :on-change="handleChangePic"
            list-type="picture"
            drag
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">Drop file here or <em>click to upload</em></div>
            <template #tip>
              <div class="el-upload__tip">jpg/jpeg/png files with a size less than 3mb</div>
            </template>
          </el-upload>
        </el-form-item>
        <!-- 置顶 -->
        <el-form-item label="置顶">
          <el-switch v-model="props.editInfo.is_sticky" />
        </el-form-item>
        <!-- 推荐 -->
        <el-form-item label="推荐">
          <el-switch v-model="props.editInfo.is_recommend" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="articleStore.editVisibleController(false)">取消</el-button>
          <el-button type="primary" @click="onSubmitArticle(editArticleRef)"> 发表 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup name="editDialog">
  import { UploadFilled } from '@element-plus/icons-vue'
  import type { UploadProps, UploadInstance, FormRules, FormInstance } from 'element-plus'
  import { reactive, ref } from 'vue'
  import useArticleStore from '@/store/article'
  import notification from '@/utils/notification'
  import { uploadCoverRequest, updateArticleContentRequest } from '@/network/api/article-api'
  const articleStore = useArticleStore()
  const props = defineProps<{
    editInfo: any
    types: any
    labels: any
  }>()
  // 表单ref对象
  const editArticleRef = ref<FormInstance>()
  // 表单 校验规则
  const rules = reactive<FormRules>({
    article_title: [
      { required: true, message: '标题为必填项~', trigger: 'change' },
      { min: 3, max: 40, message: '标题长度在3-40个字符~', trigger: 'change' },
    ],
    article_labels: [
      {
        required: true,
        message: '标签为必选项~',
        trigger: 'change',
      },
    ],
    article_type: [
      {
        required: true,
        message: '类型为必选项~',
        trigger: 'change',
      },
    ],
  })
  // 上传组件ref对象
  const uploadEdit = ref<UploadInstance>()
  let isUpload = ref(false)

  const diaLogClose = () => {
    editArticleRef.value?.resetFields()
    uploadEdit.value?.clearFiles()
  }

  // 上传图片之前的回调，限制上传大小和上传类型
  const beforeUpload: UploadProps['beforeUpload'] = rawFile => {
    console.log('上传封面之前的回调')

    const type = ['image/jpeg', 'image/jpg', 'image/png']
    if (type.indexOf(rawFile.type) === -1) {
      notification.warning('文章封面图片类型必须是以下格式：JPG/JPEG/PNG format!')
      return false
    } else if (rawFile.size / 1024 / 1024 > 3) {
      notification.error('图片大小不能超过 3MB!')
      return false
    }
    return true
  }

  // 限制图片数量
  //限制只上传一个文件
  const handleChangePic = (file: any, fileList: any) => {
    if (fileList.length > 1) {
      fileList.splice(0, 1)
    }
    isUpload.value = true
  }

  // 上传图片事件
  const uploadAction = async (param: any) => {
    // console.log('在这里上传封面')
    // console.log(articleStore.article_id)
    const { file } = param
    const formData = new FormData()
    formData.append('cover', file)
    const result = await uploadCoverRequest(formData, props.editInfo.article_id)
    notification.success(result.msg)
    articleStore.articleFormVisible = false
  }

  const onSubmitArticle = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        const result = await updateArticleContentRequest(props.editInfo.article_id, props.editInfo)
        notification.success(result.msg)
        articleStore.editVisibleController(false)
        // 如果有上传 更新封面
        if (isUpload.value) {
          uploadEdit.value?.submit()
          isUpload.value = false
        }
      } else {
        return
      }
    })
  }
</script>

<style lang="less" scoped></style>
